package com.zhang.common.file;


import com.aliyun.oss.ClientConfiguration;
import com.aliyun.oss.OSSClient;
import com.aliyun.oss.common.auth.CredentialsProvider;
import com.aliyun.oss.common.auth.DefaultCredentialProvider;
import com.aliyun.oss.model.ObjectMetadata;
import com.zhang.common.util.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;
import org.springframework.web.multipart.MultipartFile;

import javax.activation.MimetypesFileTypeMap;
import javax.annotation.PostConstruct;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.URL;
import java.util.Date;

/**
 * AliyunOssManager
 *
 * @author zhangxin
 * @date 2021/6/18
 */
@Component
public class AliyunOssManager implements IFileManager {
    protected static final Logger log = LoggerFactory.getLogger(AliyunOssManager.class);

    @Value("${aliyun.oss.bucketName}")
    private String bucketName;
    @Value("${aliyun.oss.accessKeyId}")
    private String accessKeyId;
    @Value("${aliyun.oss.accessKeySecret}")
    private String accessKeySecret;
    @Value("${aliyun.oss.endpoint}")
    private String endpoint;
    private static OSSClient ossClient = null;


    public AliyunOssManager() {
    }

    public String put(MultipartFile multipartFile, String destSliceFile) throws IOException {
        InputStream multipartFileInputStream = multipartFile.getInputStream();
        return this.uploadFileOSS(multipartFileInputStream, destSliceFile);
    }

    public String put(String localFile, String destSliceFile) throws IOException {
        File file = new File(localFile);
        InputStream inputStream = new FileInputStream(file);
        return this.uploadFileOSS(inputStream, destSliceFile);
    }


    public boolean exist(String destSliceFile) throws IOException {
        boolean result = false;

        try {
            ossClient.deleteObject(bucketName, destSliceFile);
            result = true;
        } catch (Exception var4) {
            result = false;
        }

        return result;
    }

    public InputStream get(String destFile) throws IOException {
        return null;
    }

    /**
     * 上传文件
     * @param instream
     * @param fileName
     * @return
     */
    private String uploadFileOSS(InputStream instream, String fileName) {
        String ret = "";
        try {
            //创建上传Object的Metadata
            ObjectMetadata objectMetadata = new ObjectMetadata();
            objectMetadata.setContentLength(instream.available());
            objectMetadata.setCacheControl("no-cache");
            objectMetadata.setHeader("Pragma", "no-cache");
            objectMetadata.setContentType(getContentType(fileName));
            objectMetadata.setContentDisposition("inline;filename=" + fileName);
            //上传文件
            ossClient.putObject(bucketName, fileName, instream, objectMetadata);
//            ret = putResult.getETag();
        } catch (IOException e) {
            log.error(e.getMessage(), e);
        } finally {
            try {
                if (instream != null) {
                    instream.close();
                }
                ret = getFileUrl(fileName);
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        return ret;
    }

    /**
     * 获取路径
     * @param fileName
     * @return
     */
    public String getFileUrl(String fileName) {
        if (!StringUtils.isEmpty(fileName)) {
            String[] split = fileName.split("/");
            String url =  this.getUrl(split[split.length - 1]);
            return url;
        }
        return null;
    }

    /**
     * 获得url链接
     *
     * @param key
     * @return
     */
    public String getUrl(String key) {
        // 设置URL过期时间为10年 3600l* 1000*24*365*10

        Date expiration = new Date(System.currentTimeMillis() + 3600L * 1000 * 24 * 365 * 10);
        // 生成URL
        URL url = ossClient.generatePresignedUrl(bucketName, key, expiration);
        if (url != null) {
            return url.toString();
        }
        return null;
    }

    public static String getContentType(String fileName) {

        String FilenameExtension = fileName.substring(fileName.lastIndexOf("."));
        if (FilenameExtension.equalsIgnoreCase(".bmp")) {
            return "image/bmp";
        }
        if (FilenameExtension.equalsIgnoreCase(".gif")) {
            return "image/gif";
        }
        if (FilenameExtension.equalsIgnoreCase(".jpeg") ||
                FilenameExtension.equalsIgnoreCase(".jpg") ||
                FilenameExtension.equalsIgnoreCase(".png")) {
            return "image/jpeg";
        }
        if (FilenameExtension.equalsIgnoreCase(".html")) {
            return "text/html";
        }
        if (FilenameExtension.equalsIgnoreCase(".txt")) {
            return "text/plain";
        }
        if (FilenameExtension.equalsIgnoreCase(".vsd")) {
            return "application/vnd.visio";
        }
        if (FilenameExtension.equalsIgnoreCase(".pptx") ||
                FilenameExtension.equalsIgnoreCase(".ppt")) {
            return "application/vnd.ms-powerpoint";
        }
        if (FilenameExtension.equalsIgnoreCase(".docx") ||
                FilenameExtension.equalsIgnoreCase(".doc")) {
            return "application/msword";
        }
        if (FilenameExtension.equalsIgnoreCase(".xml")) {
            return "text/xml";
        }
        return (new MimetypesFileTypeMap()).getContentType(fileName);
    }



    @PostConstruct
    public void init(){
        try {
            CredentialsProvider cp = new DefaultCredentialProvider(accessKeyId, accessKeySecret);
            ossClient = new OSSClient(endpoint, cp, (ClientConfiguration)null);
            if (!ossClient.doesBucketExist(bucketName)) {
                ossClient.createBucket(bucketName);
            }

        } catch (Exception var1) {
        }
    }
}
